<template>
  <a-layout-header class="header">
    <div class="header-container">
      <a-row :wrap="false" class="header-row">
        <!-- 左侧：Logo和标题 -->
        <a-col flex="200px">
          <RouterLink to="/">
            <div class="header-left">
              <img alt="Logo" class="logo" src="@/assets/logo.png" />
              <h1 class="site-title">零码智绘</h1>
            </div>
          </RouterLink>
        </a-col>
        <!-- 中间：导航菜单 -->
        <a-col flex="auto">
          <a-menu
            v-model:selectedKeys="selectedKeys"
            :items="menuItems"
            mode="horizontal"
            @click="handleMenuClick"
          />
        </a-col>
        <!-- 右侧：用户操作区域 -->
        <a-col>
          <div class="user-login-status">
            <div v-if="loginUserStore.loginUser.id">
              <a-dropdown placement="bottomRight">
                <a class="user-dropdown-trigger" @click.prevent>
                  <a-space>
                    <a-avatar :src="loginUserStore.loginUser.userAvatar" />
                    {{ loginUserStore.loginUser.userName ?? '匿名用户' }}
                  </a-space>
                </a>
                <template #overlay>
                  <a-menu @click="handleUserMenuClick">
                    <a-menu-item key="profile">
                      <UserOutlined />
                      个人信息
                    </a-menu-item>
                    <a-menu-item key="settings">
                      <SettingOutlined />
                      设置
                    </a-menu-item>
                    <a-menu-divider />
                    <a-menu-item key="logout">
                      <LogoutOutlined />
                      退出登录
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
            <div v-else>
              <a-button
                type="primary"
                size="middle"
                @click="router.push('/user/login')"
                class="login-btn"
              >
                <UserOutlined />
                登录
              </a-button>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
  </a-layout-header>
</template>

<script lang="ts" setup>
import { computed, h, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { MenuProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { UserOutlined, SettingOutlined, LogoutOutlined } from '@ant-design/icons-vue'
import { routes } from '@/router'
import checkAccess from '@/access/checkAccess'
import { userLogout } from '@/api/userController'

// JS 中引入 Store
import { useLoginUserStore } from '@/stores/loginUser.ts'

const loginUserStore = useLoginUserStore()

const router = useRouter()
// 当前选中菜单
const selectedKeys = ref<string[]>(['/'])
// 监听路由变化，更新当前选中菜单
router.afterEach((to) => {
  selectedKeys.value = [to.path]
})

// 根据路由配置自动生成菜单项，并根据权限过滤
const menuItems = computed(() =>
  routes
    .filter((route) => {
      // 如果设置了隐藏菜单，则不显示
      if (route.meta?.hideInMenu) {
        return false
      }
      // 根据用户权限过滤菜单项
      return checkAccess(loginUserStore.loginUser, route.meta?.access as string)
    })
    .map((route) => {
      // 如果是外部链接
      if (route.meta?.href) {
        return {
          key: route.path,
          label: h('a', { href: route.meta.href, target: '_blank' }, route.meta.title),
          title: route.name,
        }
      }
      // 内部路由链接
      return {
        key: route.path,
        label: route.name,
        title: route.name,
      }
    }),
)

// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = (e) => {
  const key = e.key as string
  selectedKeys.value = [key]
  // 跳转到对应页面
  if (key.startsWith('/')) {
    router.push(key)
  }
}

// 处理用户下拉菜单点击
const handleUserMenuClick: MenuProps['onClick'] = async (e) => {
  const key = e.key as string
  switch (key) {
    case 'profile':
      // 跳转到个人信息页面
      router.push('/user/center')
      break
    case 'settings':
      // 跳转到设置页面
      router.push('/user/settings')
      break
    case 'logout':
      // 执行退出登录
      await handleLogout()
      break
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    const res = await userLogout()
    if (res.data.code === 0) {
      message.success('退出登录成功')
      // 清除本地用户信息
      loginUserStore.setLoginUser({
        userName: '未登录',
      })
      // 跳转到登录页面
      router.push('/user/login')
    } else {
      message.error('退出登录失败：' + res.data.message)
    }
  } catch {
    message.error('退出登录失败')
    // 即使API调用失败，也清除本地用户信息
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    router.push('/user/login')
  }
}
</script>

<style scoped>
.header {
  background: #fff;
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.header-row {
  height: 64px;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  height: 48px;
  width: 48px;
}

.site-title {
  margin: 0;
  font-size: 18px;
  color: #6c5ce7;
  font-weight: 600;
}

.user-dropdown-trigger {
  color: rgba(0, 0, 0, 0.85);
  cursor: pointer;
  transition: all 0.3s;
  padding: 8px 12px;
  border-radius: 6px;
  text-decoration: none !important;
}

.user-dropdown-trigger:hover {
  color: #6c5ce7;
  background-color: rgba(108, 92, 231, 0.06);
}

.ant-menu-horizontal {
  border-bottom: none !important;
}

/* 菜单选中和悬停样式 */
:deep(.ant-menu-horizontal .ant-menu-item-selected) {
  color: #6c5ce7 !important;
  border-bottom-color: #6c5ce7 !important;
}

:deep(.ant-menu-horizontal .ant-menu-item:hover) {
  color: #6c5ce7 !important;
  border-bottom-color: #6c5ce7 !important;
}

/* 修复下划线颜色 - 针对伪元素 */
:deep(.ant-menu-horizontal .ant-menu-item-selected::after) {
  border-bottom-color: #6c5ce7 !important;
}

:deep(.ant-menu-horizontal .ant-menu-item:hover::after) {
  border-bottom-color: #6c5ce7 !important;
}

:deep(.ant-menu-horizontal .ant-menu-item-active) {
  color: #6c5ce7 !important;
}

/* 针对链接元素的样式 */
:deep(.ant-menu-horizontal .ant-menu-item-selected a) {
  color: #6c5ce7 !important;
}

:deep(.ant-menu-horizontal .ant-menu-item:hover a) {
  color: #6c5ce7 !important;
}

/* 移除我们添加的额外边框，只修改原有下划线颜色 */
:deep(.ant-menu.ant-menu-horizontal .ant-menu-item-selected) {
  color: #6c5ce7 !important;
  border-bottom-color: #6c5ce7 !important;
}

:deep(.ant-menu.ant-menu-horizontal .ant-menu-item:hover) {
  color: #6c5ce7 !important;
  border-bottom-color: #6c5ce7 !important;
}

.user-login-status {
  display: flex;
  align-items: center;
  height: 64px;
}

/* 登录按钮样式 */
.login-btn {
  background: #6c5ce7;
  border-color: #6c5ce7;
  color: #fff;
  transition: all 0.3s ease;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(108, 92, 231, 0.3);
}

.login-btn:hover {
  background: #5a4fcf;
  border-color: #5a4fcf;
  color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(108, 92, 231, 0.4);
}
</style>
